<template>
    <select v-model="wantedId" class="form-control">
        <option value="">请选择</option>
        <option v-for="(item, key) in options" :value="key" :selected="item===value">{{item}}</option>
        <input type="hidden" :name="name" :value="options[wantedId]">
    </select>
</template>

<script>
    export default {
        name: "SelectInput",
        props:{
            area:Object,    //全局变量，其实就是 china-area-data
            name:String,    //本级列表的名称
            sun:String,     //下级列表的名称
            value:String,   //数据保持功能专用
        },
        computed:{
            options(){
                this.wantedId=''    //本行将下级清零
                return this.area[this.area[this.name+'Id']]|| {}
            },
        },
        data(){
            return{
                wantedId:'',
            }
        },
        watch:{
            wantedId(){
                this.$set(this.area, this.sun+'Id', this.wantedId)
            },
        },
        mounted(){
            this.$set(this.area, this.sun+'Id', '') //本行纠正一个bug
            this.init()                             //数据保持功能专用
        },
        methods:{
            init(){// 实现数据保持（即便提交的表单没能通过验证，之前选过的省市区信息也会得到保留，无需重选）
                setTimeout(()=>{
                    if(this.value)
                        for(let wantedId in this.options){
                            if(this.options[wantedId]===this.value){
                                return this.wantedId=wantedId
                            }
                        }
                })
            }
        }
    }
</script>

<style scoped lang="stylus">
    select
        padding-right:2px
        padding-left:8px
</style>